package com.four.seckill.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: hxw
 * @Date: 2022/01/11/15:06
 * @Description
 */
@Component
public class OssUtils {


    public static String uploadFile(MultipartFile file) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tCpWHAyLPhXsjYzvWr3";
        String accessKeySecret = "jqLddNUzmys1EPgrHUyTNMSA9VIAxr";
        // host的格式为 bucketname.endpoint
        String baseUrl = "https://gulimall-1020-1904a.oss-cn-shanghai.aliyuncs.com/";

// 填写Bucket名称，例如examplebucket。
        String bucketName = "gulimall-1020-1904a";
        if (!file.isEmpty()) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            // 用户上传文件时指定的前缀。
            String dir = format.format(new Date()) + "/";

            String fileName = file.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
            String uuid = UUID.randomUUID().toString();
            extName = uuid + "." + extName;
            /**
             * 创建OSSClient实例
             */
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            try {
                String fileUri = dir + extName;
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUri, file.getInputStream());
                ossClient.putObject(putObjectRequest);
                String fileRealUrl = baseUrl + "/" + fileUri;
                return fileRealUrl;

            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                ossClient.shutdown();
            }
            return null;
        } else {
            return null;
        }

    }
}
